//
//  QHMediaUtil.m
//  QHMediaLiveDemo
//
//  Created by qihuichen on 2022/6/26.
//

#import "QHMediaUtil.h"

@implementation QHMediaUtil

+ (NSURL *)createWatermarkFolder {
    NSURL *url = [[NSFileManager defaultManager] URLsForDirectory:NSCachesDirectory inDomains:NSUserDomainMask].firstObject;
    url = [url URLByAppendingPathComponent:@"QF_LM_MASK"];
    NSFileManager * fileManager = [NSFileManager defaultManager];
    if (![fileManager fileExistsAtPath:url.path]) {
        [fileManager createDirectoryAtURL:url withIntermediateDirectories:YES attributes:nil error:nil];
    }
    return url;
}

+ (NSURL *)watermark:(CGSize)s {
    NSURL *url = [QHMediaUtil createWatermarkFolder];
    NSString *text = @"陈陈陈";
    NSURL *path = [url URLByAppendingPathComponent:[NSString stringWithFormat:@"%@_%.0f_%.0f_v921.png", text, s.width, s.height]];
//    if (kTest4Self) {
//        if ([[NSFileManager defaultManager] fileExistsAtPath:path.path]) {
//            [[NSFileManager defaultManager] removeItemAtURL:path error:nil];
//        }
//    }
    if (![[NSFileManager defaultManager] fileExistsAtPath:path.path]) {

        CGFloat ff = 8;
        UIFont *f = [UIFont systemFontOfSize:ff];
        CGSize expectedLabelSize = CGSizeZero;
        while (YES) {
            if (expectedLabelSize.height != 0 && expectedLabelSize.height > s.height) {
                f = [UIFont boldSystemFontOfSize:(ff - 1)];
                break;
            }
            else if (ff > 20) {
                break;
            }
            ff += 2;
            f = [UIFont boldSystemFontOfSize:ff];
            expectedLabelSize = [@"陈" boundingRectWithSize:CGSizeMake(100, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName: f} context:nil].size;
        }

        UILabel *l = [UILabel new];
        l.frame = CGRectMake(0, 0, s.width, s.height);
        l.font = f;
        l.text = text;
        l.textColor = [UIColor orangeColor];
        l.backgroundColor = [UIColor clearColor];
        l.shadowColor = [UIColor colorWithWhite:0 alpha:0.5];
        l.shadowOffset = CGSizeMake(1, 1);

        UIGraphicsBeginImageContextWithOptions(CGSizeMake(s.width, s.height), NO, [UIScreen mainScreen].scale);
        CGContextRef ctx = UIGraphicsGetCurrentContext();
//        CGContextSetInterpolationQuality(ctx, kCGInterpolationHigh);
        [l.layer renderInContext:ctx];
        UIImage* image = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        
        
        NSData *data = UIImagePNGRepresentation(image);
        BOOL b = [data writeToURL:path atomically:YES];
        NSLog(@"%s-%@-%ld", __func__, path, (long)b);
    }
    return path;
}

@end
